{% extends "template/page.html" %}

{% block title %}{{ title }}{% endblock %}
{% block page_title %}{{ title }}{% endblock %}

{% block soft %}open{% endblock %}
{% block category %}active{% endblock %}

{% block body%}
<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-toolbar clearfix">
                <div class="toolbar-btn-action">
                    <button class="btn btn-success m-r-5" id="refreshBtn"><i class="mdi mdi-refresh"></i> 刷新</button>
                    <button class="btn btn-primary m-r-5" id="addCateBtn"  data-toggle="modal" data-target="#addCategory"><i class="mdi mdi-plus"></i> 新建分类</button>
                    <button class="btn btn-danger m-r-5" id="delManyBtn"><i class="mdi mdi-close"></i> 批量删除</button>
                    <div class="modal fade" id="addCategory" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header" id="myModalLabel">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                                    <h4 class="modal-title">添加分类</h4>
                                </div>
                                <div class="modal-body" id="addCategoryBody">
                                    <form id="addCateForm">
                                        <div class="form-group">
                                            <label for="cateName">分类名称</label>
                                            <input type="text" class="form-control" id="CateName" placeholder="请输入分类名称">
                                        </div>
                                        <div class="form-group">
                                            <label for="cateName">分类描述</label>
                                            <textarea class="form-control" id="CateDesc" placeholder="请输入分类描述，可空"></textarea>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                    <button type="button" class="btn btn-success" data-dismiss="modal" id="addCateSubBtn">提交</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal fade" id="editCategory" tabindex="-1" role="dialog" aria-labelledby="emyModalLabel">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header" id="emyModalLabel">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                                    <h4 class="modal-title">编辑分类</h4>
                                </div>
                                <div class="modal-body" id="editCategoryBody">
                                    <form id="editCateForm">
                                        <div class="form-group">
                                            <label for="cateName">分类名称</label>
                                            <input type="text" class="form-control" id="eCateName" placeholder="请输入分类名称">
                                        </div>
                                        <div class="form-group">
                                            <label for="cateName">分类描述</label>
                                            <textarea class="form-control" id="eCateDesc" placeholder="请输入分类描述，可空"></textarea>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                    <button type="button" class="btn btn-success" data-dismiss="modal" id="editCateSubBtn">确认修改</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="categoryTable">
                        <thead>
                            <tr>
                                <th>
                                    <label class="lyear-checkbox checkbox-primary">
                                        <input type="checkbox" id="check-all"><span></span>
                                    </label>
                                </th>
                                <th>序号</th>
                                <th>分类名称</th>
                                <th>频道数量</th>
                                <th>分类描述</th>
                                <th>包含频道</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                <ul class="pagination" id="pagination"></ul>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block script %}
<script>
    // 编辑分类
    function editFunction(id) {
         nowId = id;
         $('#eCateName').val($('#cname' + nowId).text());
         $('#eCateDesc').val($('#cdesc' + nowId).text());
    }
</script>
<script>
    $(document).ready(function () {
        var ids = [];
        var totalPages = {{ allPages }};
        var currentPage = 1;

        var nowCateId = -1;
        $('#editCateSubBtn').on('click', function(event) {
            event.preventDefault();
            $.ajax({
                url: '/api/soft/editCategory',
                type: 'POST',
                data: {
                    id: nowId,
                    name: $('#eCateName').val(),
                    desc: $('#eCateDesc').val()
                },
                success: function (response) {
                    if (response.code == 200) {
                        lightyear.notify(response.msg, 'success', 2000);
                        refreshDeviceList(currentPage);
                   } else {
                        lightyear.notify(response.msg, 'danger', 2000);
                        refreshDeviceList(currentPage);
                   }
                },
                error: function() {
                    lightyear.notify("网络错误或服务器无响应", 'danger', 2000);
                    refreshDeviceList(currentPage);
                },
            });
        });

        // 获取所有分类页数
        function getCategoryPageNum() {
            $.ajax({
                url: '/api/soft/getCategoryPageNum',
                type: 'GET',
                success: function (response) {
                    if (response.code == 200) {
                        totalPages = response.data;
                    }
                }
            });
        }

        // 刷新按钮
        $('#refreshBtn').on('click', function () {
            refreshDeviceList(currentPage);
            lightyear.notify("刷新成功", 'success', 1000);
        });
        // 全选或取消全选
        $('#check-all').on('change', function () {
            var isChecked = $(this).is(':checked');
            $('input[type="checkbox"][name="ids[]"]').prop('checked', isChecked);
            ids = isChecked ? $('input[type="checkbox"][name="ids[]"]').map(function () {
                return this.value;
            }).get() : [];
        });

        // 数据表单ids登记与解除
        $('#categoryTable').on('change', 'input[type="checkbox"][name="ids[]"]', function () {
            var id = $(this).val();
            if ($(this).is(':checked')) {
                ids.push(id);
            } else {
                var index = ids.indexOf(id);
                if (index !== -1) {
                    ids.splice(index, 1);
                }
            }
        });
        // 刷新分类列表
        function refreshDeviceList(page) {
            var page = currentPage;
            lightyear.loading('show');
            ids = [];
            getCategoryPageNum();
            generatePagination(totalPages, currentPage);
            // 所有checkBox取消勾选
            $('input[type="checkbox"]').prop('checked', false);
            $.ajax({
                url: '/api/soft/getCategoriesByPage',
                type: 'GET',
                data: { "page": page },
                success: function (response) {
                    if (response.code == 200) {
                        // 清空列表
                        $('#categoryTable tbody').empty();
                        // 添加数据
                        response.data.forEach(function (category) {
                            var row = `
                        <tr>
                            <td>
                                <label class="lyear-checkbox checkbox-primary">
                                    <input type="checkbox" name="ids[]" value="${category.id}"><span></span>
                                </label>
                            </td>
                            <td>${category.num}</td>
                            <td id="cname${category.id}">${category.name}</td>
                            <td>${category.channelsNum}</td>
                            <td id="cdesc${category.id}">${category.desc}</td>
                            <td>${category.channels}</td>
                            <td>
                          <div class="btn-group">
                            <a class="btn btn-xs btn-default" data-toggle="modal" data-target="#editCategory" onclick="editFunction(${category.id})" data-original-title="编辑"><i class="mdi mdi-pencil"></i></a>
                          </div>
                        </td>
                        </tr>
                    `;
                            $('#categoryTable tbody').append(row);
                        });
                        lightyear.loading('hide');
                    }
                    else {
                        lightyear.loading('hide');
                        lightyear.notify("刷新失败：" + response.msg, 'danger', 2000);
                    }
                },
                error: function () {
                    lightyear.loading('hide');
                    lightyear.notify('网络错误或服务器无响应', 'danger', 2000);
                }
            });
        }

        // 生成分页符
        function generatePagination(totalPages, currentPage) {
            var paginationHtml = '<ul class="pagination">';
            // 上一页
            if (currentPage > 1) {
                paginationHtml += '<li><a href="#" data-page="' + (currentPage - 1) + '">«</a></li>';
            } else {
                paginationHtml += '<li class="disabled"><span>«</span></li>';
            }
            // 显示页码
            var startPage = 1;
            var endPage = totalPages;
            var maxPagesToShow = 9; // 显示的最大页码数
            if (totalPages > maxPagesToShow) {
                var middlePage = Math.floor(maxPagesToShow / 2);
                startPage = Math.max(currentPage - middlePage, 1);
                endPage = startPage + maxPagesToShow - 1;

                if (endPage > totalPages) {
                    endPage = totalPages;
                    startPage = endPage - maxPagesToShow + 1;
                }
            }
            for (var page = startPage; page <= endPage; page++) {
                if (page === currentPage) {
                    paginationHtml += '<li class="active"><span>' + page + '</span></li>';
                } else {
                    paginationHtml += '<li><a href="#" data-page="' + page + '">' + page + '</a></li>';
                }
            }
            // 省略号
            if (startPage > 1) {
                paginationHtml += '<li class="disabled"><span>...</span></li>';
            }
            if (endPage < totalPages) {
                paginationHtml += '<li class="disabled"><span>...</span></li>';
            }
            // 下一页
            if (currentPage < totalPages) {
                paginationHtml += '<li><a href="#" data-page="' + (currentPage + 1) + '">»</a></li>';
            } else {
                paginationHtml += '<li class="disabled"><span>»</span></li>';
            }
            paginationHtml += '</ul>';
            $('#pagination').html(paginationHtml);
        }
         generatePagination(totalPages, currentPage);
        // 点击分页链接
        $(document).on('click', '.pagination a', function (e) {
            e.preventDefault();
            var page = $(this).data('page');
            currentPage = page;
            refreshDeviceList(page); // 调用函数刷新设备列表
            $('.pagination-container').html(generatePagination(totalPages, currentPage)); // 重新生成分页控件
        });
        // 绑定分页点击事件
        $('#pagination').on('click', 'a[data-page]', function(e) {
            e.preventDefault();
            var page = parseInt($(this).data('page'));
            if (!$(this).parent().hasClass('disabled') && !$(this).parent().hasClass('active')) {
                currentPage = page;
                refreshDeviceList(page);
                generatePagination(totalPages, currentPage);
            }
        });
        // 添加分类
        $('#addCateSubBtn').on('click', function (event) {
            $.ajax({
                url: '/api/soft/addCategory',
                type: 'POST',
                data: {
                    CateName: $('#CateName').val(),
                    CateDesc: $('#CateDesc').val(),
                },
                success: function (response) {
                    if (response.code === 200) {
                        lightyear.notify(response.msg, 'success', 2000);
                        refreshDeviceList(currentPage);
                        $('#CateName').val("");
                        $('#CateDesc').val("");
                    } else {
                        lightyear.notify(response.msg, 'danger', 2000);
                        refreshDeviceList(currentPage);
                        $('#CateName').val("");
                        $('#CateDesc').val("");
                    }
                },
                error: function () {
                    lightyear.notify("网络错误或服务器无响应", 'danger', 2000);
                    refreshDeviceList(currentPage);
                    $('#CateName').val("");
                    $('#CateDesc').val("");
                },
            });
        });
        // 删除分类
        $('#delManyBtn').on('click', function (event) {
            $.ajax({
                url: '/api/soft/deleteCategory',
                type: 'POST',
                data: {
                    "ids":JSON.stringify(ids),
                },
                success: function (response) {
                    if (response.code === 200) {
                        lightyear.notify(response.msg, 'success', 2000);
                        refreshDeviceList(currentPage);
                   } else {
                        lightyear.notify(response.msg, 'danger', 2000);
                        refreshDeviceList(currentPage);
                   }
                },
                error: function () {
                    lightyear.notify("网络错误或服务器无响应", 'danger', 2000);
                    refreshDeviceList(currentPage);
                },
            });
        });
        refreshDeviceList(currentPage);
    });
</script>
{% endblock %}